#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File   : a_iterator.py
# @Email  : xuexia_xu@feidee.com
# @Time   : 2024/3/20 17:21
# @Desc   : map、reduce、filter使用
from functools import reduce


# 1. map使用
def f(x):
    return x * x


r = map(f, range(1, 10))
print(list(r))


# 规范英文名字
def normalize(name):
    return name.capitalize()


L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

# 2. filter使用  1到10内的偶数
L = list(filter(lambda x: x % 2 == 1, range(1, 20)))
print(L)


# 3. reduce使用 把序列[1, 3, 5, 7, 9]变换成整数13579
def fn(x, y):
    print("x:", x)
    return x * 10 + y


print("reduce:", reduce(fn, range(1, 10, 2)))


# 利用reduce求乘积
def prod(L):
    return reduce(lambda x, y: x * y, L)


print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')


# 利用map和reduce编写一个str2float函数，把字符串'123.456'转换成浮点数123.456
def str2float(s):
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

    s1, s2 = s.split('.')

    def str2num(s):
        return DIGITS[s]

    def num2float(a, b):
        return a * 10 + b

    part1 = reduce(num2float, map(str2num, s1))  # 整数部分
    part2 = reduce(num2float, map(str2num, s2))  # 小数部分
    return part1 + part2 * (0.1 ** len(s2))


print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')


# 寻找列表的最小值和最大值
def findMinAndMax(L):
    if not L:
        return None, None
    else:
        return min(L), max(L)
